package com.year.shiyi.service.impl;

import com.year.shiyi.common.utils.Constant;
import com.year.shiyi.entity.mybatis.SysMenuEntity;
import com.year.shiyi.entity.mybatis.SysRoleEntity;
import com.year.shiyi.entity.mybatis.SysUserEntity;
import com.year.shiyi.service.ShiroService;
import com.year.shiyi.service.SysMenuService;
import com.year.shiyi.service.SysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shiyi on 2021/2/23 16:25
 */
@Service
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public Set<String> getUserPermissions(long userId) {

        List<String> permsList = new ArrayList<>();
        Set<String> set = new HashSet<>();
        List<SysRoleEntity> entities = sysRoleService.listRoleByUserId(userId);
        if (entities != null && entities.size() > 0) {
            Optional<SysRoleEntity> first = entities.stream().filter(x -> x.getRoleName().equals(Constant.SUPER_ADMIN)).findFirst();
            if (first.isPresent()) {
                permsList = sysMenuService.list().stream().map(SysMenuEntity::getPerms).collect(Collectors.toList());
            } else {
                permsList = sysMenuService.queryAllPermsByUserId(userId);
            }

            for (String perms : permsList) {
                if (StringUtils.isBlank(perms)) {
                    continue;
                }
                set.addAll(Arrays.asList(perms.trim().split(",")));
            }
        }
        return set;
    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        return null;
    }
}
